const express = require('express')
const { query } = require('../utils/pool')
const router = express.Router()
// 医院添加
router.post('/add', async (req, res, next) => {
  const obj = req.body
  try {
    var result = await query('insert into ih_hospital set ?', [obj])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  res.send({ code: 200, msg: '医院添加成功' })
})

// 医院列表
router.get('/list', async (req, res, next) => {
  const obj = req.query;
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 10;
  const size = parseInt(obj.count);
  const start = (obj.pno - 1) * size;
  try {
    let sql
    if (obj.title || obj.grade) {
      if (obj.title) {
        sql = `select * from ih_hospital where title like '%${obj.title}%' limit ?,?;select count(*) as n from ih_hospital where title like '%${obj.title}%'`
      } else if (obj.grade) {
        sql = `select * from ih_hospital where grade=${obj.grade} limit ?,?;select count(*) as n from ih_hospital where grade=${obj.grade}`
      } else {
        sql = `select * from ih_hospital where title like '%${obj.title}%' and grade=${obj.grade} limit ?,?;select count(*) as n from ih_hospital where title like '%${obj.title}%' and grade=${obj.grade}`
      }
    } else {
      sql = 'select * from ih_hospital limit ?,?;select count(*) as n from ih_hospital'
    }
    console.log(sql)
    var result = await query(
      sql,
      [start, size]
    )
  } catch (err) {
    return next(err)
  };
  console.log(result);
  res.send({
    code: 200,
    msg: '医院列表',
    data: result[0],
    total: result[1][0].n,
    pno: obj.pno
  });
})

// 医院修改
router.put('/update', async (req, res, next) => {
  const obj = req.body
  const { id } = obj
  try {
    var result = await query('update ih_hospital set ? where id=?', [obj, id])
  } catch (err) {
    return next(err)
  }
  if (result.changedRows === 0) {
    res.send({ code: 400, msg: '修改失败' })
  } else {
    res.send({ code: 200, msg: '修改成功' })
  }
})
// 删除医院
router.delete('/', async (req, res, next) => {
  const { id } = req.query
  try {
    var result = await query('delete from ih_hospital where id=?', [id])
  } catch (err) {
    return next(err)
  }
  if (result.affectedRows === 0) {
    res.send({ code: 400, msg: '删除失败' })
  } else {
    res.send({ code: 200, msg: '删除成功' })
  }
})

module.exports = router